#!/usr/bin/python3
# coding=utf-8

from utils.logger_helper import logObj
import requests
import json
import sys

sys.path.append("./")

class RequestsUtil:

    session = requests.Session()

    def send_api_request(self, **kwargs):
        res = RequestsUtil.session.request(**kwargs)
        return res


class RequestsHelper:
    def __init__(self):
        self.req = requests.Session()
        self.header = {
            "Content-Type": "application/json",
            "accept": "application/json",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36",
            "Connection": "keep-alive",
        }
        self.verify = False
        self.timeout = 60
        self.allow_redirects = False

    @property
    def token(self):
        return self._token

    @token.setter
    def token(self, token):
        """Reset Token info and update headers
        :param token: User's Token information
        :type token: string
        """
        self._token = token if token else None
        # add token into headers
        if self._token:
            self.header["token"] = self._token
        else:
            if "token" in self.header.keys():
                del self.header["token"]

    @property
    def cookie(self):
        return self._cookie

    @cookie.setter
    def cookie(self, cookie):
        """Reset Cookie info and update headers
        :param cookie: User's Token information
        :type cookie: string
        """
        self._cookie = cookie if cookie else None
        # add cookie into headers
        if self._cookie:
            self.header["cookie"] = self._cookie
        else:
            if "cookie" in self.header.keys():
                del self.header["cookie"]

    def get_req(self, url, headers=None, params=None, data=None, **kwargs):
        # print(self.headers)
        req_header = headers if headers else self.header
        resp_obj = self.req.get(
            url,
            headers=req_header,
            params=params,
            data=data,
            timeout=self.timeout,
            verify=self.verify,
            allow_redirects=self.allow_redirects,
        )
        # http_info = {
        #     'URL': url,
        #     'Req_headers': req_header,
        #     'Req_method': 'GET',
        #     'Req_params': params,
        #     'Resp_headers': resp_obj.headers,
        #     'Resp_Body': resp_obj.text
        # }
        http_info = {
            "URL": url,
            "Req_method": "GET",
            "Req_Param": params,
            "Req_body": data,
            "Resp_Body": json.loads(resp_obj.text),
        }
        # Logger.debug(f'接口请求信息: {http_info}')
        logObj.debug("接口请求信息: {}".format(http_info))
        self.connection_close()
        return resp_obj

    def post_req(self, url, headers, params=None, data=None, **kwargs):
        """http request with post method
        :param url: URL
        :type url: string
        :param payload: parameters with get request
        :type payload: dict
        :param token: include user's access info
        :type token: string
        :return result: response object
        :rtype result: json.loads(response.text)
        """
        # print(self.headers)
        req_header = headers if headers else self.header
        resp_obj = self.req.post(
            url,
            headers=req_header,
            params=params,
            data=json.dumps(data),
            timeout=self.timeout,
            verify=self.verify,
            allow_redirects=self.allow_redirects,
        )
        # http_info = {
        #     'URL': url,
        #     'Req_headers': req_header,
        #     'Req_method': 'POST',
        #     'Req_body': data,
        #     'Resp_headers': resp_obj.headers,
        #     'Resp_Body': resp_obj.text
        # }
        http_info = {
            "URL": url,
            "Req_method": "POST",
            "Req_Param": params,
            "Req_body": data,
            "Resp_Body": json.loads(resp_obj.text),
        }
        # Logger.debug(f'接口请求信息: {http_info}')
        logObj.debug("接口请求信息: {}".format(http_info))
        self.connection_close()
        return resp_obj

    def put_req(self, url, headers, params=None, data=None, **kwargs):
        # print(self.headers)
        req_header = headers if headers else self.header
        resp_obj = self.req.put(
            url,
            headers=req_header,
            params=params,
            data=json.dumps(data),
            timeout=self.timeout,
            verify=self.verify,
            allow_redirects=self.allow_redirects,
        )
        # http_info = {
        #     'URL': url,
        #     'Req_headers': req_header,
        #     'Req_method': 'PUT',
        #     'Req_body': data,
        #     'Resp_headers': resp_obj.headers,
        #     'Resp_Body': resp_obj.text
        # }
        http_info = {
            "URL": url,
            "Req_method": "PUT",
            "Req_Param": params,
            "Req_body": data,
            "Resp_Body": json.loads(resp_obj.text),
        }
        # Logger.debug(f'接口请求信息: {http_info}')
        logObj.debug("接口请求信息: {}".format(http_info))
        self.connection_close()
        return resp_obj

    def delete_req(self, url, headers=None, params=None, data=None, **kwargs):
        # print(self.headers)
        req_header = headers if headers else self.header
        resp_obj = self.req.delete(
            url,
            headers=req_header,
            params=params,
            data=json.dumps(data),
            timeout=self.timeout,
            verify=self.verify,
            allow_redirects=self.allow_redirects,
        )
        http_info = {
            "URL": url,
            "Req_headers": req_header,
            "Req_method": "DELETE",
            "Req_body": data,
            "Resp_headers": resp_obj.headers,
            "Resp_Body": json.loads(resp_obj.text),
        }
        # Logger.debug(f'接口请求信息: {http_info}')
        logObj.debug("接口请求信息: {}".format(http_info))
        self.connection_close()
        return resp_obj

    def upload_post_req(
        self, url, headers=None, files=None, params=None, data=None, **kwargs
    ):
        # 临时改造的FormData 格式的API 接口的实现方式
        # headers = None
        resp_obj = self.req.post(
            url, headers=headers, data=data, files=files, params=params
        )
        http_info = {
            "URL": url,
            "Req_headers": headers,
            "Req_method": "POST",
            "Req_body": data,
            "files": files,
            "Resp_Body": json.loads(resp_obj.text),
        }
        # Logger.debug(f'接口请求信息: {http_info}')
        logObj.debug("接口请求信息: {}".format(http_info))
        self.connection_close()
        return resp_obj

    def connection_close(self):
        """主动关闭连接"""
        self.req.close()


if __name__ == "__main__":
    session = RequestsHelper()
    # header = {
    #     'content-type':'application/json'
    # }
    # data = {
    #     'user':19413131313,
    #     'pwd':'aB123456',
    #     'captcha': ''
    # }
    # print(json.dumps(data))
    # print(session.post_req('http://billing.paas-t.xforceplus.com/api/internal/login', headers=header, json = json.dumps(data)))
    url = "http://billing.paas-t.xforceplus.com/api/normal/login"

    data = {
        "username": "19715461546",
        "password": "vgzQ2KHLn7+3CO5fR7gB/Q==",
        "captcha": "",
    }
    print(type(data))
    headers = {
        "Content-Type": "application/json",
    }

    response = requests.post(url, headers=headers, json=data)

    print(response.json())
